package com.taysear.bus;

import java.util.Date;
import java.util.HashMap;

import com.taysear.bus.util.Constants;
import com.taysear.bus.util.Results;
import com.taysear.bus.util.Util;
import com.taysear.dbservice.DbServicesPrx;
import com.taysear.dbservice.ServiceParameter;
import com.taysear.dbservice.ServiceResult;
import com.taysear.domain.Loadingsheet;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.util.BeanContainer;
import com.vaadin.ui.Button;
import com.vaadin.ui.Component;
import com.vaadin.ui.CustomLayout;
import com.vaadin.ui.DateField;
import com.vaadin.ui.Form;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Table;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Table.ColumnGenerator;
import com.vaadin.ui.themes.Runo;

@SuppressWarnings("serial")
public class BusManifestOutgoing extends HorizontalLayout {

	Form form = new Form(); 
	HorizontalLayout actionButtons = new HorizontalLayout();
	Button routeDetailsBtn = new Button("Route details");
	Button routeTimesBtn = new Button("Route times");
	Table table = new Table();
	
	Boolean isSaved = false;
	
	public BusManifestOutgoing() {
		setSpacing(true);
		
		CustomLayout manageLayout = new CustomLayout("manageBusManifest");
		
		form.setCaption("Outgoing bus manifest");
		manageLayout.addComponent(form, "form");

		DateField date = new DateField("Date", new Date());
		date.setRequired(true);
		date.setRequiredError("This field is required");
		date.setWidth(Constants.COMMON_FIELD_WIDTH_M);
		date.setImmediate(true);
		date.setDateFormat(Constants.DATE_FORMAT_STRING);
		date.setResolution(DateField.RESOLUTION_DAY);
		form.addField("date", date);
		
		Button searchBtn = new Button("Search");
		searchBtn.addStyleName("blueButton");
		searchBtn.setDisableOnClick(true);
		searchBtn.addListener(new Button.ClickListener() {
		    @Override
		    public void buttonClick(ClickEvent event) {
		    	if(form.isValid())
		    		loadBusManifestData();
		    	else
		    		AppData.getApp().showErrorNotification(Constants.ME_FORM_FIELDS_REQUIRED);
		    	event.getButton().setEnabled(true);
		    }
		});
		form.getFooter().addComponent(searchBtn);
		
		actionButtons.setSpacing(true);
		
		final Button addBtn = new Button("Add");
		addBtn.addStyleName("greenButton");
		addBtn.setDisableOnClick(true);
		addBtn.addListener(new Button.ClickListener() {
		    @Override
		    public void buttonClick(ClickEvent event) {
		    	 
		    	event.getButton().setEnabled(true);
		    }
		});
		actionButtons.addComponent(addBtn);
		
		final Button editBtn = new Button("Edit");
		editBtn.addStyleName("greenButton");
		editBtn.setEnabled(false);
		editBtn.setDisableOnClick(true);
		editBtn.addListener(new Button.ClickListener() {
		    @Override
		    public void buttonClick(ClickEvent event) {
		    	
		    	event.getButton().setEnabled(true);
		    }
		});
		actionButtons.addComponent(editBtn);
		
		routeDetailsBtn.setVisible(false);
		routeDetailsBtn.setEnabled(false);
		routeDetailsBtn.addStyleName("blueButton");
		routeDetailsBtn.setDisableOnClick(true);
		routeDetailsBtn.addListener(new Button.ClickListener() {
		    @Override
		    public void buttonClick(ClickEvent event) {
		    	event.getButton().setEnabled(true);
		    }
		});
		actionButtons.addComponent(routeDetailsBtn);
		
		routeTimesBtn.setVisible(false);
		routeTimesBtn.setEnabled(false);
		routeTimesBtn.addStyleName("blueButton");
		routeTimesBtn.setDisableOnClick(true);
		routeTimesBtn.addListener(new Button.ClickListener() {
		    @Override
		    public void buttonClick(ClickEvent event) {
		    	event.getButton().setEnabled(true);
		    }
		});
		actionButtons.addComponent(routeTimesBtn);

		table.addStyleName(Runo.TABLE_SMALL);
		table.setSizeFull();
		table.setVisible(false);
		table.setSelectable(true);
		table.setPageLength(Constants.PAGE_SIZE);
		table.setImmediate(true);
		table.setWidth("760px");
		table.addListener(new ValueChangeListener() {
			@Override
			public void valueChange(ValueChangeEvent event) {
				// add or edit only allowed today, yesterday and any date in the future
				Date today = Util.setDateHourAndMinute(new Date(), 0, 0, false);
				//Date yesterday = new Date(cal.getTimeInMillis());
				if(event.getProperty().getValue() != null ) {
					editBtn.setEnabled(true);
				} else {
					editBtn.setEnabled(false);
				}
			}
		});
		table.addGeneratedColumn("Id", new ColumnGenerator() {
			  public Component generateCell(Table source, Object itemId, Object columnId) {
				  String id = "loadingsheetId";
			      if (table.getItem(itemId).getItemProperty(id).getValue() != null) {
			          Label l = new Label();
			          l.setValue(table.getItem(itemId).getItemProperty(id).getValue());
			          l.setWidth("50px");
			          return l;
			      }
			      return null;
			  }
			});
		table.addGeneratedColumn("Origin", new ColumnGenerator() {
			  public Component generateCell(Table source, Object itemId, Object columnId) {
				  String id = "originName";
			      if (table.getItem(itemId).getItemProperty(id).getValue() != null) {
			          Label l = new Label();
			          l.setValue(table.getItem(itemId).getItemProperty(id).getValue());
			          l.setWidth("150px");
			          return l;
			      }
			      return null;
			  }
			});
		table.addGeneratedColumn("Destination", new ColumnGenerator() {
			  public Component generateCell(Table source, Object itemId, Object columnId) {
				  String id = "destinationName";
			      if (table.getItem(itemId).getItemProperty(id).getValue() != null) {
			          Label l = new Label();
			          l.setValue(table.getItem(itemId).getItemProperty(id).getValue());
			          l.setWidth("150px");
			          return l;
			      }
			      return null;
			  }
			});
		table.addGeneratedColumn("Bus", new ColumnGenerator() {
			  public Component generateCell(Table source, Object itemId, Object columnId) {
				  String id = "busRegistrationNumber";
			      if (table.getItem(itemId).getItemProperty(id).getValue() != null) {
			          Label l = new Label();
			          l.setValue(table.getItem(itemId).getItemProperty(id).getValue());
			          l.setWidth("70px");
			          return l;
			      }
			      return null;
			  }
			});
		table.addGeneratedColumn("Driver", new ColumnGenerator() {
			  public Component generateCell(Table source, Object itemId, Object columnId) {
				  String id = "driverName";
			      if (table.getItem(itemId).getItemProperty(id).getValue() != null) {
			          Label l = new Label();
			          l.setValue(table.getItem(itemId).getItemProperty(id).getValue());
			          l.setWidth("150px");
			          return l;
			      }
			      return null;
			  }
			});
		table.addGeneratedColumn("Conductor", new ColumnGenerator() {
			  public Component generateCell(Table source, Object itemId, Object columnId) {
				  String id = "conductorName";
			      if (table.getItem(itemId).getItemProperty(id).getValue() != null) {
			          Label l = new Label();
			          l.setValue(table.getItem(itemId).getItemProperty(id).getValue());
			          l.setWidth("150px");
			          return l;
			      }
			      return null;
			  }
			});
		table.addGeneratedColumn("Status", new ColumnGenerator() {
			  public Component generateCell(Table source, Object itemId, Object columnId) {
				  String id = "loadingsheetStatusName";
			      if (table.getItem(itemId).getItemProperty(id).getValue() != null) {
			          Label l = new Label();
			          l.setValue(table.getItem(itemId).getItemProperty(id).getValue());
			          return l;
			      }
			      return null;
			  }
			});
		table.addGeneratedColumn("Time", new ColumnGenerator() {
			  public Component generateCell(Table source, Object itemId, Object columnId) {
				  String id = "routeTimeName";
			      if (table.getItem(itemId).getItemProperty(id).getValue() != null) {
			          Label l = new Label();
			          l.setValue(table.getItem(itemId).getItemProperty(id).getValue());
			          l.setWidth("50px");
			          return l;
			      }
			      return null;
			  }
			});
		
		manageLayout.addComponent(actionButtons, "actionButtons");
		manageLayout.addComponent(table, "result");
		addComponent(manageLayout);
	}
	
	/**
	 * Loads loadingsheets/busmanifest from database into a table view.
	 */
	private void loadBusManifestData() {
		BusApplication app = AppData.getApp();
		ServiceParameter sp = new ServiceParameter(new HashMap<String, String>());
		sp.param.put("startDate", Util.formatDateForDB(Util.getStartOfADay((Date)form.getField("date").getValue())));
		sp.param.put("endDate", Util.formatDateForDB(Util.getEndOfADay((Date)form.getField("date").getValue())));
		
		BeanContainer<Integer, Loadingsheet> container = new BeanContainer<Integer, Loadingsheet>(Loadingsheet.class);
		container.setBeanIdProperty("loadingsheetId");
		
		DbServicesPrx dbServicesPrx = app.getDbServiceProxy();
		ServiceResult sr = dbServicesPrx.getLoadingsheetByDates(sp);
		if(sr.status) {
			if(sr.param.get("RECORDS") != null) {
				Results r = Util.getObjectsFromXmlResult(sr.param.get("RECORDS"), Loadingsheet.class);
				for (Object object : r.getRows()) {
					Loadingsheet o = (Loadingsheet) object;
					container.addItem(o.getLoadingsheetId(), o);
				}
				table.setContainerDataSource(container);
				table.setVisible(true);
				table.setVisibleColumns(Constants.columnsBusManifestTable);
			} else {
				table.setContainerDataSource(null);
				table.setVisible(false);
				app.showNotification(Constants.MN_NO_RESULT);
			}
		} else {
			app.showErrorNotification(sr.message);
			table.setContainerDataSource(null);
			table.setVisible(false);
		}
	}
	
}
